<?php
// -----------------------------------------------------
// Created by : php-task
// -----------------------------------------------------
// User: tf <1096392101@qq.com>
// -----------------------------------------------------
declare (strict_types=1);

namespace Gao\Task\handler;

//套接字
class Socket
{

    protected $config = [
        'port' => 6655, //端口
        'address' => '127.0.0.1', //IP地址
    ];

    //服务端
    public function socket_server()
    {
        if(($sock = socket_create(AF_INET,SOCK_STREAM,SOL_TCP)) < 0) {
            echo "socket_create() 失败的原因是:".socket_strerror((int)$sock)."\n";
        }

        if(($ret = socket_bind($sock,$this->config['address'],$this->config['port'])) < 0) {
            echo "socket_bind() 失败的原因是:".socket_strerror((int)$ret)."\n";
        }

        if(($ret = socket_listen($sock,4)) < 0) {
            echo "socket_listen() 失败的原因是:".socket_strerror((int)$ret)."\n";
        }

        $count = 0;

        do {
            if (($msgsock = socket_accept($sock)) < 0) { //socket_accept 接受套接字连接
                echo "socket_accept() failed: reason: " . socket_strerror((int)$msgsock) . "\n";
                break;
            } else {
                socket_set_nonblock($msgsock);//非阻塞
                //发到客户端
                $msg ="测试成功！\n";
                socket_write($msgsock, $msg, strlen($msg));

                $buf = socket_read($msgsock,8192);//读取客户端内容

                //收到内容发到客户端
                socket_write($msgsock, $buf, strlen($msg));

                if(++$count >= 5){
                    break;
                };

            }
            //echo $buf;
            socket_close($msgsock);

        } while (true);

        socket_close($sock);
    }

    //客户端
    public function socket_client()
    {
        $socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
        if ($socket < 0) {
            echo "socket_create() failed: reason: " . socket_strerror((int)$socket) . "\n";
        }else {
            echo "OK.\n";
        }
        $ip = $this->config['address'];
        $port = $this->config['port'];
        echo "试图连接 $ip 端口 $port. \n";
        $result = socket_connect($socket, $ip,$port);
        if ($result < 0) {
            echo "socket_connect() failed.\nReason: ($result) " . socket_strerror((int)$result) . "\n";
        }else {
            echo "连接OK\n";
        }

        $in = "hello socket";
        $out = '';

        if(!socket_write($socket, $in, strlen($in))) {
            echo "socket_write() failed: reason: " . socket_strerror((int)$socket) . "\n";
        }else {
            echo "发送到服务器信息成功！\n";
            echo "发送的内容为:$in";
        }

        while($out = socket_read($socket, 8192)) {
            echo "接收服务器回传信息成功！\n";
            echo "接受的内容为:",$out;
        }

        echo "关闭SOCKET...\n";
        socket_close($socket);
        echo "关闭OK\n";
    }


}